<template>
  <div class="student-request-container">
    <el-card class="header-card" shadow="hover">
      <div class="page-header">
        <div class="title-section">
          <el-icon :size="28" color="#409EFF"><Tickets /></el-icon>
          <h2>我的诉求</h2>
        </div>
        <el-button type="primary" @click="showSubmitDialog = true">
          <el-icon><Plus /></el-icon>
          提交新诉求
        </el-button>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-row">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <el-icon :size="32" color="#909399"><Clock /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.pending || 0 }}</div>
            <div class="stat-label">待处理</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <el-icon :size="32" color="#E6A23C"><Loading /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.processing || 0 }}</div>
            <div class="stat-label">处理中</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <el-icon :size="32" color="#67C23A"><Select /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.resolved || 0 }}</div>
            <div class="stat-label">已解决</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <el-icon :size="32" color="#F56C6C"><CloseBold /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.rejected || 0 }}</div>
            <div class="stat-label">已拒绝</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="hover">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" @change="fetchRequests" clearable style="width: 180px">
            <el-option label="全部" value="ALL" />
            <el-option label="待处理" value="PENDING" />
            <el-option label="处理中" value="PROCESSING" />
            <el-option label="已解决" value="RESOLVED" />
            <el-option label="已拒绝" value="REJECTED" />
          </el-select>
        </el-form-item>
        <el-form-item label="诉求类型">
          <el-select v-model="filterForm.requestType" placeholder="请选择诉求类型" @change="fetchRequests" clearable style="width: 180px">
            <el-option label="全部" value="ALL" />
            <el-option label="成绩申诉" value="GRADE" />
            <el-option label="选课问题" value="COURSE" />
            <el-option label="课表问题" value="SCHEDULE" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchRequests">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 诉求列表 -->
    <el-card class="table-card" shadow="hover">
      <el-table :data="requestList" v-loading="loading" stripe border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="title" label="诉求标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="requestType" label="类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getRequestTypeColor(scope.row.requestType)">
              {{ getRequestTypeName(scope.row.requestType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusColor(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getPriorityColor(scope.row.priority)" size="small">
              {{ getPriorityName(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submitTime" label="提交时间" width="180" align="center" />
        <el-table-column prop="adminName" label="处理人" width="120" align="center">
          <template #default="scope">
            {{ scope.row.adminName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewDetail(scope.row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.status !== 'PENDING'"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 提交诉求对话框 -->
    <el-dialog v-model="showSubmitDialog" title="提交新诉求" width="600px">
      <el-form :model="submitForm" :rules="submitRules" ref="submitFormRef" label-width="100px">
        <el-form-item label="诉求类型" prop="requestType">
          <el-select v-model="submitForm.requestType" placeholder="请选择诉求类型" style="width: 100%">
            <el-option label="成绩申诉" value="GRADE" />
            <el-option label="选课问题" value="COURSE" />
            <el-option label="课表问题" value="SCHEDULE" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item label="诉求标题" prop="title">
          <el-input v-model="submitForm.title" placeholder="请输入诉求标题" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="详细内容" prop="content">
          <el-input 
            v-model="submitForm.content" 
            type="textarea" 
            :rows="6" 
            placeholder="请详细描述您的诉求内容" 
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-radio-group v-model="submitForm.priority">
            <el-radio label="LOW">低</el-radio>
            <el-radio label="NORMAL">普通</el-radio>
            <el-radio label="HIGH">高</el-radio>
            <el-radio label="URGENT">紧急</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="相关课程" prop="relatedCourseName">
          <el-input v-model="submitForm.relatedCourseName" placeholder="如涉及具体课程，请填写课程名称（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSubmitDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="诉求详情" width="700px">
      <div v-if="currentRequest" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="诉求标题" :span="2">{{ currentRequest.title }}</el-descriptions-item>
          <el-descriptions-item label="诉求类型">
            <el-tag :type="getRequestTypeColor(currentRequest.requestType)">
              {{ getRequestTypeName(currentRequest.requestType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusColor(currentRequest.status)">
              {{ getStatusName(currentRequest.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityColor(currentRequest.priority)">
              {{ getPriorityName(currentRequest.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ currentRequest.submitTime }}</el-descriptions-item>
          <el-descriptions-item label="相关课程" :span="2">
            {{ currentRequest.relatedCourseName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="详细内容" :span="2">
            <div class="content-text">{{ currentRequest.content }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="处理人" v-if="currentRequest.adminName">
            {{ currentRequest.adminName }}
          </el-descriptions-item>
          <el-descriptions-item label="处理时间" v-if="currentRequest.processTime">
            {{ currentRequest.processTime }}
          </el-descriptions-item>
          <el-descriptions-item label="解决时间" v-if="currentRequest.resolveTime" :span="2">
            {{ currentRequest.resolveTime }}
          </el-descriptions-item>
          <el-descriptions-item label="管理员回复" :span="2" v-if="currentRequest.adminReply">
            <el-alert :title="currentRequest.adminReply" type="success" :closable="false" />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button type="primary" @click="showDetailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Tickets, Plus, Clock, Loading, Select, CloseBold, 
  Search, Refresh, View, Delete 
} from '@element-plus/icons-vue'
import { submitRequest, getMyRequests, deleteRequest } from '../api/request'

// 用户信息
const user = JSON.parse(localStorage.getItem('user') || '{}')
const userId = user.studentId || user.student_id || user.id
const userName = user.stuName || user.name

// 数据
const loading = ref(false)
const submitting = ref(false)
const requestList = ref([])
const showSubmitDialog = ref(false)
const showDetailDialog = ref(false)
const currentRequest = ref(null)
const submitFormRef = ref(null)

// 统计数据
const stats = computed(() => {
  const pending = requestList.value.filter(r => r.status === 'PENDING').length
  const processing = requestList.value.filter(r => r.status === 'PROCESSING').length
  const resolved = requestList.value.filter(r => r.status === 'RESOLVED').length
  const rejected = requestList.value.filter(r => r.status === 'REJECTED').length
  return { pending, processing, resolved, rejected }
})

// 筛选表单
const filterForm = reactive({
  status: 'ALL',
  requestType: 'ALL'
})

// 提交表单
const submitForm = reactive({
  requestType: 'GRADE',
  title: '',
  content: '',
  priority: 'NORMAL',
  relatedCourseName: ''
})

// 表单验证规则
const submitRules = {
  requestType: [{ required: true, message: '请选择诉求类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入诉求标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入详细内容', trigger: 'blur' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }]
}

// 获取诉求列表
const fetchRequests = async () => {
  try {
    loading.value = true
    console.log('🔍 获取诉求列表参数:', { userId, userType: 'STUDENT', user })
    
    if (!userId) {
      ElMessage.error('未找到用户ID，请先登录')
      loading.value = false
      return
    }
    
    const res = await getMyRequests({
      userId,
      userType: 'STUDENT',
      status: (!filterForm.status || filterForm.status === 'ALL') ? null : filterForm.status
    })
    
    if (res.code === 200) {
      let list = res.data || []
      
      // 前端筛选类型
      if (filterForm.requestType && filterForm.requestType !== 'ALL') {
        list = list.filter(item => item.requestType === filterForm.requestType)
      }
      
      requestList.value = list
    } else {
      ElMessage.error(res.message || '获取诉求列表失败')
    }
  } catch (error) {
    console.error('获取诉求列表失败:', error)
    ElMessage.error('获取诉求列表失败')
  } finally {
    loading.value = false
  }
}

// 提交诉求
const handleSubmit = async () => {
  try {
    await submitFormRef.value.validate()
    
    submitting.value = true
    const res = await submitRequest({
      ...submitForm,
      userId,
      userType: 'STUDENT',
      userName
    })
    
    if (res.code === 200) {
      ElMessage.success('诉求提交成功')
      showSubmitDialog.value = false
      resetSubmitForm()
      fetchRequests()
    } else {
      ElMessage.error(res.message || '提交失败')
    }
  } catch (error) {
    if (error !== false) { // 表单验证失败会返回false
      console.error('提交诉求失败:', error)
      ElMessage.error('提交失败')
    }
  } finally {
    submitting.value = false
  }
}

// 重置提交表单
const resetSubmitForm = () => {
  submitForm.requestType = 'GRADE'
  submitForm.title = ''
  submitForm.content = ''
  submitForm.priority = 'NORMAL'
  submitForm.relatedCourseName = ''
  submitFormRef.value?.clearValidate()
}

// 重置筛选
const resetFilter = () => {
  filterForm.status = 'ALL'
  filterForm.requestType = 'ALL'
  fetchRequests()
}

// 查看详情
const viewDetail = (row) => {
  currentRequest.value = row
  showDetailDialog.value = true
}

// 删除诉求
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条诉求吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteRequest(row.requestId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchRequests()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除诉求失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 辅助函数
const getRequestTypeName = (type) => {
  const map = { GRADE: '成绩申诉', COURSE: '选课问题', SCHEDULE: '课表问题', OTHER: '其他' }
  return map[type] || type
}

const getRequestTypeColor = (type) => {
  const map = { GRADE: 'danger', COURSE: 'warning', SCHEDULE: 'primary', OTHER: 'info' }
  return map[type] || 'info'
}

const getStatusName = (status) => {
  const map = { PENDING: '待处理', PROCESSING: '处理中', RESOLVED: '已解决', REJECTED: '已拒绝' }
  return map[status] || status
}

const getStatusColor = (status) => {
  const map = { PENDING: 'info', PROCESSING: 'warning', RESOLVED: 'success', REJECTED: 'danger' }
  return map[status] || 'info'
}

const getPriorityName = (priority) => {
  const map = { LOW: '低', NORMAL: '普通', HIGH: '高', URGENT: '紧急' }
  return map[priority] || priority
}

const getPriorityColor = (priority) => {
  const map = { LOW: 'info', NORMAL: '', HIGH: 'warning', URGENT: 'danger' }
  return map[priority] || ''
}

onMounted(() => {
  fetchRequests()
})
</script>

<style scoped>
.student-request-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-section h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 10px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.detail-content {
  padding: 10px;
}

.content-text {
  white-space: pre-wrap;
  line-height: 1.8;
  color: #606266;
}
</style>

